<script setup>
import { ref, reactive, toRefs, computed, nextTick } from "vue";
import planApi from "@/api/planApi";
import freeTestApi from "@/api/freeTestApi.js"
import { Message } from "@arco-design/web-vue";
import Upload from "@/components/Upload.vue";

const addFreeTestVisible = ref(false)
const historyParams = history.state.params;
const searchForm = ref();
const searchModel = reactive({
    planId: historyParams.planId,
    gradeId: "",
    freeTestFlag: false,
});

const uploadFreeTestVisible = ref(false);
const uploadBatchFreeTestVisible = ref(false)
const searchFreeForm = ref();
const searchFreeModel = reactive({
    planId: historyParams.planId,
});
const submitData = ref({
    schoolName: '',
    name: '',
    studyCode: '',
    sex: '',
    defaultScore: true,
    studyCodes:''
})
const submitForm = ref()

const freeLoading = ref(false)
const loading = ref(false)

let pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 15,
    showPageSize: true,
    pageSizeOptions: [15, 25, 30, 50],
    showTotal: true,
    pageChange: (current) => {
        pagination.current = current;
        search();
    },
    pageSizeChange(size) {
        pagination.pageSize = size;
        search();
    },
});

let freePagination = reactive({
    total: 0,
    current: 1,
    pageSize: 120,
    showPageSize: true,
    pageSizeOptions: [120, 320, 480, 960],
    showTotal: true,
    pageChange: (current) => {
        freePagination.current = current;
        searchFree();
    },
    pageSizeChange(size) {
        freePagination.pageSize = size;
        searchFree();
    },
});

const freeColumns = [
    {
        title: "学校名称",
        dataIndex: "schoolName",
        width: 150,
    },
    {
        title: "学生姓名",
        dataIndex: "name",
        width: 100,
    },
    {
        title: "性别",
        slotName: "sex",
        width: 100,
    },

    {
        title: "年级",
        dataIndex: "gradeName",
        width: 100,
    },
    {
        title: "班级",
        dataIndex: "classesName",
        width: 100,
    },
    {
        title: "学籍号",
        dataIndex: "studyCode",
        width: 200,
    },
    {
        title: "免考项目",
        dataIndex: "projectName",
        width: 100,
    },
    {
        title: "原因",
        dataIndex: "reason",
        width: 100,
    },
    {
        title: "得分",
        dataIndex: "score",
        width: 100,
    },
    {
        title: "录入时间",
        dataIndex: "createTime",
        width: 180,
    },
    {
        title: "操作",
        slotName: "action",
        fixed: "right",
        width: 200,
    },
];

const importFreeTestData = () => {
    uploadFreeTestVisible.value = true;
};

const importBatchFreeTestData = () => {
    uploadBatchFreeTestVisible.value = true;
}

const data = ref([]);
const freeData = ref([])

let uploadData = ref({
  planId: historyParams.planId,
});

const search = () => {
    var params = {
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryParam: Object.assign({}, searchModel),
    };
    loading.value = true;
    planApi.pageStudent(params).then((res) => {
        data.value = res.records;
        pagination.total = res.total;
        loading.value = false;
    });
};

const searchFree = () => {
    var params = {
        pageNo: freePagination.current,
        pageSize: freePagination.pageSize,
        queryParam: Object.assign({}, searchFreeModel),
    };
    freeLoading.value = true;
    freeTestApi.queryPage(params).then((res) => {
        freeData.value = res.records;
        freePagination.total = res.total;
        freeLoading.value = false;
    });
};


const openAddDialog = () => {
    addFreeTestVisible.value = true;
    nextTick(() => {
        searchStudyCode.value = ''
        submitData.value = {
            schoolName: '',
            name: '',
            studyCode: '',
            sex: '',
            defaultScore: true
        };
        submitForm.value.resetFields()
    })
}

const querying = ref(false);
const saving = ref(false);
const searchStudyCode = ref('')
const queryStudentInfoByStudyCode = () => {
    querying.value = true;
    planApi.queryStudentInfoByStudyCode({
        planId: historyParams.planId,
        studyCode: searchStudyCode.value
    }).then(res => {
        submitData.value = Object.assign(submitData.value, res);
        querying.value = false;
    }).catch(() => {
        querying.value = false;
    })
}

const saveFreeTest = () => {
    saving.value = true;
    planApi.saveFreeTest(submitData.value).then(res => {
        addFreeTestVisible.value = false;
        saving.value = false;
        Message.success("保存成功")
    }).catch(() => {
        saving.value = false;
    })
}

const batchSaveFreeTest = () => {
    if(!submitData.value.studyCodes || !submitData.value.studyCodes.trim()){
        return;
    }
    submitData.value.planId = historyParams.planId
    saving.value = true;
    planApi.saveFreeTestForNoScore(submitData.value).then(res => {
        uploadBatchFreeTestVisible.value = false;
        saving.value = false;
        Message.success("保存成功")
        searchFree();
    }).catch(() => {
        saving.value = false;
    })
}

const deleteFreeRecord = (record) => {
    freeTestApi
        .delete({
            id: record.id,
        })
        .then((res) => {
            searchFree();
        });
};

searchFree();

</script>
<template>
    <div class="main-con">
        <a-card>
            <a-row>
                <a-col :flex="1">
                    <a-form ref="searchFreeForm" :model="searchFreeModel" :label-col-props="{ span: 8 }"
                        :wrapper-col-props="{ span: 16 }" label-align="left">
                        <a-row :gutter="16">
                            <a-col :span="8">
                                <a-form-item field="schoolId" label="学校">
                                    <a-select v-model="searchFreeModel.schoolId" placeholder="请选择学校" allow-clear
                                        @change="schoolSelectChange">
                                        <a-option v-for="school in schoolList" :value="school.id" :key="school.id"
                                            :label="school.name"></a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item field="name" label="学生姓名">
                                    <a-input v-model="searchFreeModel.name" placeholder="请输入姓名" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="16">
                            <a-col :span="8">
                                <a-form-item field="sex" label="性别">
                                    <a-select v-model="searchFreeModel.sex" placeholder="请选择性别">
                                        <a-option value="1">男</a-option>
                                        <a-option value="2">女</a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item field="studyCode" label="学籍号">
                                    <a-input v-model="searchFreeModel.studyCode" placeholder="请输入学籍号" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
                <a-divider style="height: 84px" direction="vertical" />
                <a-col :flex="'86px'" style="text-align: right">
                    <a-space direction="vertical" :size="18">
                        <a-button type="primary" @click="searchFree">
                            <template #icon>
                                <icon-search />
                            </template>
                            查询
                        </a-button>
                        <a-button @click="searchFreeForm.value.resetFields()">
                            <template #icon>
                                <icon-refresh />
                            </template>
                            重置
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>
        </a-card>
        <a-card>
            <div class="toolbar">
                <a-space>
                    <a-button type="primary" @click="openAddDialog">
                        <template #icon>
                            <icon-plus />
                        </template>
                        新增免考
                    </a-button>
                    <a-button type="outline" @click="importBatchFreeTestData">
                        <template #icon>
                            <icon-upload />
                        </template>
                        批量新增免考
                    </a-button>
                    <a-button type="outline" @click="importFreeTestData">
                        <template #icon>
                            <icon-upload />
                        </template>
                        导入免考学生
                    </a-button>
                </a-space>
            </div>
            <a-table :columns="freeColumns" :loading="freeLoading" :data="freeData"
                @page-change="freePagination.pageChange" @page-size-change="freePagination.pageSizeChange"
                :pagination="freePagination" :bordered="false">
                <template #sex="{ record }">
                    {{ record.sex == "1" ? "男" : "女" }}
                </template>
                <template #action="{ record }">
                    <a-space>
                        <a-popconfirm content="确认要删除该数据吗？" @ok="deleteFreeRecord(record)">
                            <a-button type="text">删除</a-button>
                        </a-popconfirm>
                    </a-space>
                </template>
            </a-table>
        </a-card>
    </div>
    <a-modal v-model:visible="addFreeTestVisible" title="添加免考" width="800px" :footer="null">
        <a-form ref="submitForm" :model="submitData" auto-label-width>
            <a-form-item label="学籍号">
                <a-space>
                    <a-input-search style="width: 300px;" v-model="searchStudyCode"
                        placeholder="请输入学籍号查询"></a-input-search>
                    <a-button :loading="querying" :disabled="!searchStudyCode" @click="queryStudentInfoByStudyCode">{{
                        querying ?
                            "查询中..." :
                            '查询' }}</a-button>
                </a-space>
            </a-form-item>
            <a-form-item label="基础信息">
                <a-space>
                    <template #split>
                        <a-divider direction="vertical" />
                    </template>
                    <span v-text="'学校：' + submitData.schoolName"></span>
                    <span v-text="'学籍号：' + submitData.studyCode"></span>
                    <span v-text="'姓名：' + submitData.name"></span>
                    <span>性别：{{ submitData.sex == '1' ? '男' : '女' }}</span>
                </a-space>
            </a-form-item>
            <a-form-item label="是否默认得分">
                <a-switch v-model="submitData.defaultScore"></a-switch>
            </a-form-item>
            <a-form-item v-if="submitData.defaultScore" label="免考信息">
                <a-space direction="vertical" fill>
                    <div class="flex flex-column flex-v-center">
                        <template v-for="freeTestPrj in submitData.freeTestPrjNameList">
                            <a-space style="margin-bottom: 10px;">
                                <a-input v-model="freeTestPrj.name" readonly></a-input>
                                <a-input v-model="freeTestPrj.reason" placeholder="请输入免考/免测原因"></a-input>
                                <a-input :precision="2" placeholder="请输入得分" v-model="freeTestPrj.score"></a-input>
                            </a-space>

                        </template>
                    </div>
                </a-space>
            </a-form-item>
            <a-form-item>
                <a-button :loading="saving" type="primary" @click="saveFreeTest">{{ saving ? '正在保存..' :
                    '确认添加' }}</a-button>
            </a-form-item>
        </a-form>
    </a-modal>
    <a-modal v-model:visible="uploadFreeTestVisible" title="导入免考学生数据">
        <a-space direction="vertical" style="width: 100%; text-align: center">
            <div style="color: #999">
                暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传
            </div>
            <a-button type="link" href="/学生免考.xlsx" style="margin-bottom: 10px">导入免考学生模板下载</a-button>
            <Upload :uploadData="uploadData" :draggable="true" accept=".xls,.xlsx"
                action="/admin/v1/plan/importFreeTestData" />
        </a-space>
    </a-modal>
    <a-modal v-model:visible="uploadBatchFreeTestVisible" title="批量新增免考学生数据" @ok="batchSaveFreeTest">
        <a-space direction="vertical" style="width: 100%; text-align: center">
            <div style="color: #999">
                请将学籍号按照英文逗号隔开批量导入。比如（12312312,31231451）
            </div>
            <a-textarea placeholder="请将学籍号按照英文逗号隔开批量导入" v-model="submitData.studyCodes" auto-size allow-clear style="height: 300px;max-height: 300px;">

            </a-textarea>
        </a-space>
    </a-modal>
</template>